package com.sgcc.activiti.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.sgcc.activiti.domain.*;
import com.sgcc.activiti.service.IOInterfaceIndexService;
import com.sgcc.common.core.constant.HttpStatus;
import com.sgcc.common.core.domain.R;
import com.sgcc.common.core.text.UUID;
import com.sgcc.common.core.utils.FastJsonUtil;
import com.sgcc.common.core.utils.HttpClientUtil;
import com.sgcc.common.core.web.domain.AjaxResult;
import com.sgcc.common.core.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.sgcc.activiti.mapper.OContentAdMapper;
import com.sgcc.activiti.service.IOContentAdService;

/**
 * 广告管理结果Service业务层处理
 *
 * @author sgcc
 * @date 2021-04-07
 */
@Service
public class OContentAdServiceImpl implements IOContentAdService {

    @Value("${isTest}")
    Boolean isTest;

    @Autowired
    private OContentAdMapper oContentAdMapper;

    @Autowired
    private IOInterfaceIndexService interfaceIndexService;

    /**
     * 查询广告管理结果
     *
     * @param id 广告管理结果ID
     * @return 广告管理结果
     */
    @Override
    public OContentAd selectOContentAdById(String id) {
        return oContentAdMapper.selectOContentAdById(id);
    }

    /**
     * 查询广告管理结果列表
     *
     * @param oContentAd 广告管理结果
     * @return 广告管理结果
     */
    @Override
    public List<OContentAd> selectOContentAdList(OContentAd oContentAd) {
        return oContentAdMapper.selectOContentAdList(oContentAd);
    }

    /**
     * 新增广告管理结果
     *
     * @param oContentAd 广告管理结果
     * @return 结果
     */
    @Override
    public OContentAd insertOContentAd(OContentAd oContentAd) {
        if (null == oContentAd.getId()) {
            oContentAd.setId(UUID.randomUUID().toString().replaceAll("-", ""));
//            oContentAd.setNewId(UUID.randomUUID().toString().replaceAll("-", ""));
        }
        int i = oContentAdMapper.insertOContentAd(oContentAd);
        if (i > 0) {
            return oContentAd;
        } else {
            return null;
        }

    }

    /**
     * 修改广告管理结果
     *
     * @param oContentAd 广告管理结果
     * @return 结果
     */
    @Override
    public int updateOContentAd(OContentAd oContentAd) {
        return oContentAdMapper.updateOContentAd(oContentAd);
    }

    /**
     * 批量删除广告管理结果
     *
     * @param ids 需要删除的广告管理结果ID
     * @return 结果
     */
    @Override
    public int deleteOContentAdByIds(String[] ids) {
        return oContentAdMapper.deleteOContentAdByIds(ids);
    }

    /**
     * 删除广告管理结果信息
     *
     * @param id 广告管理结果ID
     * @return 结果
     */
    @Override
    public int deleteOContentAdById(String id) {
        return oContentAdMapper.deleteOContentAdById(id);
    }

    @Override
    public TableDataInfo operationAdvertisingManagementData(OContentAd oContentAd, Integer pageNo, Integer pageSize) {
        //1：已上架  2：已下架
        String adState = oContentAd.getAdState();
        int resultCode = 0;
        String message = "";
        String rpcResultStrTest = "";
        OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101179");
        if (null == oInterfaceIndex || null == oInterfaceIndex.getInterfaceAdress()) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setRows(null);
            rspData.setMsg("无法根据0101179获取接口");
            rspData.setTotal(0);
            return rspData;
        }
        //入参：数据起始位置
        int iDisplayStart = (pageNo - 1) * pageSize;
//        int iDisplayStart = pageNo;
        //入参：数据长度
        int iDisplayLength = pageSize;

        if (isTest) {
            resultCode = 1;
            message = "成功！";
            //远程调用广告内容列表查询接口,需求未提供调用接口，暂时使用假数据。
            if ("1".equals(adState)) {
                rpcResultStrTest = "{\n" +
                        "    \"code\": 1,\n" +
                        "    \"message\": \"成功\",\n" +
                        "    \"data\": {\n" +
                        "        \"iTotalRecords\": \"3\",\n" +
                        "        \"advList\": [\n" +
                        "            {\n" +
                        "                \"adId\": \"d735a63f148448529732e708157dd197\",\n" +
                        "                \"adName\": \"大转盘活动004\",\n" +
                        "                \"advBannerUrl\": \"/omg-static/001a3de7edd247fb9984fc8752689772.jpg\",\n" +
                        "                \"advIssueState\": \"1\",\n" +
                        "                \"advPoPicture\": \"E10141500-004\",\n" +
                        "                \"endTime\": \"2019-04-24 00:00:00\",\n" +
                        "                \"publishType\": \"2\",\n" +
                        "                \"startTime\": \"2019-04-24 00:00:00\"\n" +
                        "            },\n" +
                        "            {\n" +
                        "                \"adId\": \"f43a7fb827ee49cebfa482f5bca0f35a\",\n" +
                        "                \"adName\": \"视频05\",\n" +
                        "                \"advBannerUrl\": \"/omg-static/00110cc845394ef6abd0c8f6227d8cf8.jpg\",\n" +
                        "                \"advIssueState\": \"1\",\n" +
                        "                \"advPoPicture\": \"E10141500-86-05\",\n" +
                        "                \"endTime\": \"2019-04-25 00:19:55\",\n" +
                        "                \"publishType\": \"2\",\n" +
                        "                \"startTime\": \"2019-04-25 00:00:00\"\n" +
                        "            }\n" +
                        "        ]\n" +
                        "    }\n" +
                        "}";
            } else {
                rpcResultStrTest = "{\n" +
                        "    \"code\": 1,\n" +
                        "    \"message\": \"成功\",\n" +
                        "    \"data\": {\n" +
                        "        \"iTotalRecords\": \"3\",\n" +
                        "        \"advList\": [\n" +
                        "            {\n" +
                        "                \"adId\": \"1cbceb75dc84400ba298450adb053442\",\n" +
                        "                \"adName\": \"视频06\",\n" +
                        "                \"advBannerUrl\": \"/omg-static/00110cc845394ef6abd0c8f6227d8cf8.jpg\",\n" +
                        "                \"advIssueState\": \"2\",\n" +
                        "                \"advPoPicture\": \"E10141500-86-05\",\n" +
                        "                \"endTime\": \"2019-04-25 00:19:56\",\n" +
                        "                \"publishType\": \"2\",\n" +
                        "                \"startTime\": \"2019-04-25 00:00:00\"\n" +
                        "            }\n" +
                        "        ]\n" +
                        "    }\n" +
                        "}";
            }

            R r2 = FastJsonUtil.toBean(rpcResultStrTest, R.class);
            if (1 == r2.getCode()) {
                JSONObject data = (JSONObject) r2.getData();
                ContentAdDataListResult contentAdDataListResult = data.toJavaObject(ContentAdDataListResult.class);
                //总条数
                Long totalRecords = 0L;
                if (contentAdDataListResult.getiTotalRecords() != null && !"".equals(contentAdDataListResult.getiTotalRecords())) {
                    totalRecords= Long.valueOf(contentAdDataListResult.getiTotalRecords());
                }
                //列表数据
                List<OContentAd> advList = contentAdDataListResult.getAdvList();

                for (int i = 0; i < advList.size(); i++) {
                    OContentAd old = oContentAdMapper.selectOcontentAdByNewId(advList.get(i).getAdId());
                    if(old!=null){
                        old.setAdId(advList.get(i).getAdId());
                        old.setAdvIssueState(advList.get(i).getAdvIssueState());
                        old.setAdvIssueStateName(advList.get(i).getAdvIssueStateName());
                        old.setEndTime(advList.get(i).getEndTime());
                        old.setStartTime(advList.get(i).getStartTime());
                        old.setPublishTypeName(advList.get(i).getPublishTypeName());
                        advList.set(i,old);
                    }
                }

                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(HttpStatus.SUCCESS);
                rspData.setRows(advList);
                rspData.setMsg("查询成功");
                rspData.setTotal(totalRecords);
                return rspData;
            }
            //总条数
        } else {
            String commonParm = "";
            Map paramsData = new HashMap();
            paramsData.put("platformId", "350000");//网省平台ID:网省平台ID
            paramsData.put("releaseScope", "350000");//省份编码:网省编号
            paramsData.put("advIssueState", adState);//1：已上架  2：已下架
            paramsData.put("iDisplayStart", iDisplayStart);
            paramsData.put("iDisplayLength", iDisplayLength);

            CommonParm cparm = new CommonParm();
            cparm.setServiceCode("0101179");
            cparm.setSource("SGAPP");
            cparm.setTarget("35101");
            cparm.setData(paramsData);
            String params = FastJsonUtil.toJSONString(cparm);
            R<String> rpcResultStr = HttpClientUtil.sendJsonStr(oInterfaceIndex.getInterfaceAdress(), params);
            if (200 != rpcResultStr.getCode()) {
                TableDataInfo rspData = new TableDataInfo();
                rspData.setCode(HttpStatus.ERROR);
                rspData.setRows(null);
                rspData.setMsg(rpcResultStr.getMsg());
                rspData.setTotal(0);
                return rspData;
            }
            //解析返回值
            R r = FastJsonUtil.toBean(rpcResultStr.getData(), R.class);
            resultCode = r.getCode();

            if (resultCode == 1) {
                if (1 == r.getCode()) {
                    JSONObject data = (JSONObject) r.getData();
                    ContentAdDataListResult contentAdDataListResult = data.toJavaObject(ContentAdDataListResult.class);
                    //总条数
                    Long totalRecords = 0L;
                    if (contentAdDataListResult.getiTotalRecords() != null && !"".equals(contentAdDataListResult.getiTotalRecords())) {
                        totalRecords= Long.valueOf(contentAdDataListResult.getiTotalRecords());
                    }
                    //列表数据
                    List<OContentAd> advList = contentAdDataListResult.getAdvList();
                    for (int i = 0; i < advList.size(); i++) {
                        OContentAd old = oContentAdMapper.selectOcontentAdByNewId(advList.get(i).getAdId());
                        if(old!=null){
                            old.setAdId(advList.get(i).getAdId());
                            old.setAdvIssueState(advList.get(i).getAdvIssueState());
                            old.setAdvIssueStateName(advList.get(i).getAdvIssueStateName());
                            old.setEndTime(advList.get(i).getEndTime());
                            old.setStartTime(advList.get(i).getStartTime());
                            old.setPublishTypeName(advList.get(i).getPublishTypeName());
                            advList.set(i,old);
                        }
                    }
                    TableDataInfo rspData = new TableDataInfo();
                    rspData.setCode(HttpStatus.SUCCESS);
                    rspData.setRows(advList);
                    rspData.setMsg("查询成功");
                    rspData.setTotal(totalRecords);
                    return rspData;
                }
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.ERROR);
        rspData.setRows(null);
        rspData.setMsg("查询失败");
        rspData.setTotal(0);
        return rspData;
    }

    @Override
    public List<ContentAdPosition> getBannerAadsense(String sceneShow) {
        int resultCode = 0;
        String rpcInterface = "";
        String rpcResultStr = "";
        OInterfaceIndex oInterfaceIndex = interfaceIndexService.selectAddressbycode("0101153");
        if (null != oInterfaceIndex && null != oInterfaceIndex.getInterfaceAdress()) {
            rpcInterface = oInterfaceIndex.getInterfaceAdress();
        }
        if (true) {
            List<ContentAdPosition> contentAdPositionList = new ArrayList<>();
            ContentAdPosition contentAdPosition = new ContentAdPosition();
            contentAdPosition.setAdvPositionId("0a87fde1-d7c6-4d9a-8de6-00dc6321ead9");
            contentAdPosition.setAdvPositionName("276");
            contentAdPosition.setReleaseScope("330000");
            contentAdPositionList.add(contentAdPosition);
            ContentAdPosition contentAdPosition2 = new ContentAdPosition();
            contentAdPosition2.setAdvPositionId("95a02951-27e4-4829-b669-496d8bf349ed");
            contentAdPosition2.setAdvPositionName("277");
            contentAdPosition2.setReleaseScope("330000");
            contentAdPositionList.add(contentAdPosition2);
            return contentAdPositionList;
        } else {
            Map paramsData = new HashMap();
            paramsData.put("platformId", "350000");//网省平台ID:网省平台ID
            paramsData.put("releaseScope", "350000");//省份编码:网省编号
            paramsData.put("sceneShow", sceneShow);//3 住宅   5 店铺  6 企事业
            paramsData.put("iDisplayStart", 0);
            paramsData.put("iDisplayLength", 100);

            Map map = new HashMap();
            map.put("serviceCode", "0101153");
            map.put("source", "SGAPP");
            map.put("target", "35101");
            map.put("data", paramsData);

            String params = FastJsonUtil.toJSONString(map);
            rpcResultStr = HttpClientUtil.sendJsonStr(rpcInterface, params).getData();
            //解析返回值
            R r = FastJsonUtil.toBean(rpcResultStr, R.class);
            resultCode = r.getCode();
            if (resultCode == 1) {
                JSONObject data = (JSONObject) r.getData();
                ContentAdPositionResult contentAdPositionResult = data.toJavaObject(ContentAdPositionResult.class);
                //列表数据
                List<ContentAdPosition> contentAdPositionList = contentAdPositionResult.getBannerList();
                return contentAdPositionList;
            }
        }
        return new ArrayList<ContentAdPosition>();
    }

    @Override
    public OContentAd selectOContentAdByNewId(String newId) {
        return oContentAdMapper.selectOcontentAdByNewId(newId);
    }
}
